#!/usr/bin/env python3
"""
Setup script for Food Delivery Platform Scraper
"""

import os
import sys
import subprocess
from pathlib import Path


def check_python_version():
    """Check if Python version is compatible"""
    if sys.version_info < (3, 9):
        print("❌ Python 3.9+ is required")
        print(f"Current version: {sys.version}")
        return False
    print(f"✅ Python version: {sys.version.split()[0]}")
    return True


def check_chrome_installation():
    """Check if Chrome/Chromium is installed"""
    chrome_paths = [
        "/usr/bin/google-chrome",
        "/usr/bin/chromium-browser", 
        "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
        "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
        "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
    ]
    
    for path in chrome_paths:
        if os.path.exists(path):
            print(f"✅ Chrome found: {path}")
            return True
    
    print("⚠️  Chrome/Chromium not found in standard locations")
    print("Please install Google Chrome or Chromium browser")
    return False


def create_virtual_environment():
    """Create Python virtual environment"""
    venv_path = Path("venv")
    
    if venv_path.exists():
        print("✅ Virtual environment already exists")
        return True
    
    try:
        print("🔧 Creating virtual environment...")
        subprocess.run([sys.executable, "-m", "venv", "venv"], check=True)
        print("✅ Virtual environment created")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ Failed to create virtual environment: {e}")
        return False


def install_dependencies():
    """Install Python dependencies"""
    try:
        print("🔧 Installing dependencies...")
        
        # Determine pip path
        if os.name == 'nt':  # Windows
            pip_path = Path("venv/Scripts/pip")
        else:  # Unix/Linux/macOS
            pip_path = Path("venv/bin/pip")
        
        subprocess.run([str(pip_path), "install", "-r", "requirements.txt"], check=True)
        print("✅ Dependencies installed successfully")
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"❌ Failed to install dependencies: {e}")
        return False
    except FileNotFoundError:
        print("❌ Virtual environment not found. Please create it first.")
        return False


def create_env_file():
    """Create .env file from template"""
    env_file = Path(".env")
    env_example = Path(".env.example")
    
    if env_file.exists():
        print("✅ .env file already exists")
        return True
    
    if not env_example.exists():
        print("❌ .env.example not found")
        return False
    
    try:
        print("🔧 Creating .env file...")
        with open(env_example, 'r') as src, open(env_file, 'w') as dst:
            dst.write(src.read())
        print("✅ .env file created")
        return True
    except Exception as e:
        print(f"❌ Failed to create .env file: {e}")
        return False


def create_directories():
    """Create necessary directories"""
    directories = ["logs", "data"]
    
    for directory in directories:
        dir_path = Path(directory)
        if not dir_path.exists():
            dir_path.mkdir(parents=True, exist_ok=True)
            print(f"✅ Created directory: {directory}")
        else:
            print(f"✅ Directory exists: {directory}")
    
    return True


def run_quick_test():
    """Run quick functionality test"""
    try:
        print("🔧 Running quick functionality test...")
        
        # Determine python path
        if os.name == 'nt':  # Windows
            python_path = Path("venv/Scripts/python")
        else:  # Unix/Linux/macOS
            python_path = Path("venv/bin/python")
        
        result = subprocess.run([str(python_path), "test_scraper.py"], 
                              capture_output=True, text=True)
        
        if result.returncode == 0:
            print("✅ Quick test passed")
            return True
        else:
            print("❌ Quick test failed")
            print("Output:", result.stdout)
            print("Error:", result.stderr)
            return False
            
    except Exception as e:
        print(f"❌ Test execution failed: {e}")
        return False


def print_usage_instructions():
    """Print usage instructions"""
    print("\n" + "="*60)
    print("🎉 SETUP COMPLETE!")
    print("="*60)
    
    if os.name == 'nt':  # Windows
        activate_cmd = "venv\\Scripts\\activate"
        python_cmd = "venv\\Scripts\\python"
    else:  # Unix/Linux/macOS
        activate_cmd = "source venv/bin/activate"
        python_cmd = "venv/bin/python"
    
    print(f"""
Next steps:

1. Activate virtual environment:
   {activate_cmd}

2. Test the scraper:
   {python_cmd} test_scraper.py --full

3. Run your first scrape:
   {python_cmd} src/main.py test eleme --city 北京

4. For more options:
   {python_cmd} src/main.py --help

Configuration:
- Edit .env file to customize settings
- Check README.md for detailed usage instructions
- Review SCRAPING_STRATEGY.md for technical details

Happy scraping! 🚀
""")


def main():
    """Main setup function"""
    print("🚀 Food Delivery Platform Scraper Setup")
    print("="*50)
    
    steps = [
        ("Checking Python version", check_python_version),
        ("Checking Chrome installation", check_chrome_installation),
        ("Creating virtual environment", create_virtual_environment),
        ("Installing dependencies", install_dependencies),
        ("Creating .env file", create_env_file),
        ("Creating directories", create_directories),
    ]
    
    # Run setup steps
    for step_name, step_func in steps:
        print(f"\n🔧 {step_name}...")
        if not step_func():
            print(f"\n❌ Setup failed at: {step_name}")
            print("Please fix the issue and run setup again.")
            sys.exit(1)
    
    # Optional test
    print(f"\n🔧 Running quick test (optional)...")
    test_passed = run_quick_test()
    
    if test_passed:
        print_usage_instructions()
    else:
        print("\n⚠️  Setup completed but test failed.")
        print("You can still use the scraper, but please check the configuration.")
        print("Run 'python test_scraper.py' to diagnose issues.")


if __name__ == "__main__":
    main()
